package com.sinodata.bsm.cicp.util.telnet;

import java.util.LinkedList;
import java.util.List;

/**
 * Shell 执行结果的过滤器.</li>
 * 过滤掉ShellPrompt: (# $ > ...)
 *
 * @author thomas.h.zhang
 */
public class PromptFilter {
    public synchronized static String trimCommandPrompt(String shellOut, String shellScript, String shellPrompt) {
        List list = splitToLine(shellOut);
        trimHeadCmd(list, shellScript);
        trimTailPrompt(list, shellPrompt);
        // return linesToString(list);

        String rs = "";
        for (int i = 0; i < list.size(); i++) {
            String line = (String) list.get(i);
            //if (line.indexOf(shellPrompt) == -1)
            rs += line;
            if (i != list.size() - 1)
                rs += "\n";
        }
        return rs;
    }

    // split a string into list.
    private static List splitToLine(String shellOut) {
        String[] lines = shellOut.split("[\r\n]+");
        List list = new LinkedList();
        for (int i = 0; i < lines.length; i++) {
            list.add(lines[i]);
        }
        return list;
    }

    // 删除含有prompt的最后一行.
    private static void trimTailPrompt(List list, String shellPrompt) {
        if (list == null || list.size() == 0) {
            return;
        }

        // 删除为空的最后一行.
        int size = list.size();
        String lastLine = (String) list.get(size - 1);
        if (lastLine == null || lastLine.length() == 0) {
            list.remove(size - 1);//最后一行为空行直接先删除
        }

        //删除含有prompt的最后一行.
        size = list.size();
        lastLine = (String) list.get(size - 1);
        if (lastLine.indexOf(shellPrompt) >= 0) {
            list.remove(size - 1);// 目前的做法是直接删除最后一行.
        }
    }

    /** 过滤掉 Shell 执行结果中开头的 shell script */
    private static void trimHeadCmd(List list, String script) {
        if (list == null || list.size() == 0)
            return;
        String firstLine = (String) list.get(0);
        if (firstLine == null || firstLine.trim().equals("")) {
            list.remove(0);
        }
        for (int i = 0; i < list.size(); i++) {
            firstLine = (String) list.get(i);
            if (firstLine.trim().startsWith(script)) {
                list.remove(i);
                break;
            }
        }
    }

}